package com.tanhua.sso.service;

import com.tanhua.sso.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class HuanXinTokenService {

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    public static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String getToken() {
        if (redisTemplate.hasKey(REDIS_KEY))
            return redisTemplate.opsForValue().get(REDIS_KEY);
        String targetUrl = huanXinConfig.getUrl() + "/" +
                huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/token";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type","application/json");
        Map<String,String> map = new HashMap<>();
        map.put("grant_type","client_credentials");
        map.put("client_id",huanXinConfig.getClientId());
        map.put("client_secret",huanXinConfig.getClientSecret());
        try {
            HttpEntity<Map> httpEntity = new HttpEntity<>(map,httpHeaders);
            ResponseEntity<Map> responseEntity = restTemplate.postForEntity(targetUrl, httpEntity, Map.class);
            if (!responseEntity.getStatusCode().is2xxSuccessful()) {
                return null;
            }
            Map<String,String> result = responseEntity.getBody();
            String access_token = result.get("access_token");
            //String expires_in = result.get("expires_in");
            redisTemplate.opsForValue().set(REDIS_KEY,access_token,Duration.ofDays(5));
            return access_token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}